 /**
  * 接受数据dome处理
  * @param {Object} name 名字
  * @param {Object} face 头像
  * @param {Object} time 时间
  * @param {Object} text 内容 
  * @param {Object} state 0我发送，1我接收
  */
 function getReceive(name, face, time, text, state) {
 	var html = state == 0 ? "<div class='thread-item thread-right'>" : "<div class='thread-item'>";
 	html += "<div class='thread-avatar'><img src=" + face + " alt=''></div>";
 	html += "<div class='thread-content'>";
 	html += "<div class='thread-info'>" + name + "<span>" + time + "</span></div>";
 	html += "<div class='thread-body'>" + text + "</div></div></div>";
// 	console.log(html);
 	return html;
 }
 //将滚动条（scrollbar）保持在最底部
 function add() {
 	var div = document.getElementsByClassName("main")[0].scrollHeight;
 	document.getElementsByClassName("main")[0].scrollTop = div;
 }
 //消息返回确认封装
 function ajaxa(cid){
 	$.ajax({
 		type: "POST",
 		dataType: "json",
 		url: ip+"msg.php",
 		data: {
 			msg:1,
 			conid: cid
 		}, //40秒后无论结果服务器都返回数据
 		success: function(data, textStatus) {
 			return(data);
 		}
 	});
 } 
 /** 
  * 获取消息 
  */
 function getData() {
 	$.ajax({
 		type: "POST",
 		dataType: "json",
 		// 		url: ip+"data.php",
 		url: ip+"data.php",
 		timeout: 80000, //ajax请求超时时间80秒
 		data: {
 			m_id:m_id,
 			time: "10"
 		}, //40秒后无论结果服务器都返回数据
 		success: function(data, textStatus) {
 			//从服务器得到数据，显示数据并继续查询
 			if(data.success == "1") {
 				var lth = data.data.length;
 				
 				for(var i = 0; i < lth; i++) {
 					var name = data.data[i].name;
 					var face = data.data[i].face;
 					var time = data.data[i].time;
 					var text = data.data[i].text;
 					document.getElementsByClassName("main")[0].innerHTML += getReceive(name, face, time, text, 1);
 				    ajaxa(data.data[i].id)
 				   
 				} 
 				add();
 			}
 			//未从服务器得到数据，继续查询
 			if(data.success == "0") {
 				console.log("无数据")
 			}
 			getData();
 		},
 		//Ajax请求超时，继续查询
 		error: function(XMLHttpRequest, textStatus, errorThrown) {
 			if(textStatus == "timeout") {
 				console.log("网络原因超时")
 				getData();
 			}
 		}

 	});
 }
 /**
  * 返回数据后返回数据序号  
  * 后台收到后表示前台已读否则下次继续拉取
  * 防止网络原因导致信息丢失
  */
 document.getElementsByClassName("fa")[0].addEventListener("click",function(){
 	var text = $(".shu").val()
 
 	$.ajax({
 		type: "POST",
 		url: ip+"msg.php",
 		data: {
 			msg:2,
 			fa_id: m_id,
 			shou_id:shou_id,
 			conten:text
 		}, 
 		success: function(data) {
// 			console.log(data);
 			document.getElementsByClassName("main")[0].innerHTML += getReceive(m_name, m_face, data, text, 0);
 		},
 		error:function(data){
 			document.getElementsByClassName("main")[0].innerHTML +=  getReceive(m_name,m_face,"***","<span style='color: red;'>发送失败</span>"+text, 0);
 		}
 	});
 	$(".shu").val("");
 })
